Variables

A Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing.In Python, variables need not be declared or defined in advance, as is the case in many other programming languages.In Python variables are created the moment you assign a value to it: To create a variable, you just assign it a value and then start using it. Assignment is done with a single equals sign (=):

Declare a Variable
Number =10
Here, we have created a named number.We have assigned value 10 to the variable. You can think variable as a bag to store books in it and those books can be replaced at any time.

Re-declare a Variable
Initially, the value of  number was 10. Later it's changed to 1.1.
Number =10
Number =1.1
print(Number)

Note: In Python, we don't assign values to the variables, whereas Python gives the reference of the object (value) to the variable.

Variable name-Identifiers
Variable name is known as identifier. There are few rules that you have to follow while naming the variables in Python.
  • The name of the variable must always start with either a letter or an underscore (_). For example: _str, str, num, _num are all valid name for the variables.
  • The name of the variable cannot start with a number. For example: 9num is not a valid variable name.
  • The name of the variable cannot have special characters such as %, $, # etc, they can only have alphanumeric characters and underscore (A to Z, a to z, 0-9 or _ ).
  • Variable name is case sensitive in Python which means num and NUM are two different variables in python.
Delete a  Variable
You can also delete variable using the command del "variable name". In the example below, we deleted variable number, and when we proceed to print it, we get error "variable name is not defined" which means you have deleted the variable.  These reference to number objects can also be deleted by using del statement. The syntax for "del" statement is:
del variable_name[, variable_name2[….variable_name-N]



No comments:

Post a Comment